package com.example.demo.thread;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest {
    static Integer[] nums = new Integer[26];
    static char[] chars = new char[26];

    static volatile boolean flag = false;

    //生成测试数据A~Z,1~26
    static {
        for (int i = 0; i < 26; i++) {
            chars[i] = (char) ('A' + (i));
            nums[i] = i + 1;
        }
    }

    private static Lock lock = new ReentrantLock();
    static Condition condition1 = lock.newCondition();
    static Condition condition2 = lock.newCondition();

    public static void main(String[] args) {
        new Thread(() -> {
            printa();
        }).start();
        new Thread(() -> {
            printA();
        }).start();
    }

    private static void printa() {
        try {
            lock.lock();
            for (int i = 0; i < 26;) {
                if (flag) {
                    condition1.await();
                }
                System.out.println("thread2----" + (char) ('A' + i));
                flag = true;
                i++;
                condition2.signal();
            }
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    private static void printA() {
        try {
            lock.lock();
            for (int i = 0; i < 26;) {
                if (!flag) {
                    condition2.await();
                }
                System.out.println("thread1--" + (char) ('a' + i));
                flag = false;
                i++;
                condition1.signal();
            }
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }


}
